package business;

import java.util.Vector;

import repository.MemberRepository;
import utils.Date;
import classes.Iterator;
import classes.Member;
import exceptions.RepositoryException;

public class MemberBusiness
{
	private MemberRepository repository;
	
	public MemberBusiness() throws RepositoryException
	{
		this.repository = MemberRepository.getInstance();
	}
	
	public void add( Member member) throws RepositoryException
	{
		if( member != null )
		{
			repository.add( member );
		}
		else
		{
			throw new NullPointerException();
		}
	}
	
	public void edit( Member member ) throws RepositoryException
	{
		if( member != null )
		{
			repository.edit( member );
		}
		else
		{
			throw new NullPointerException();
		}
	}
	
	public Member get( int id ) throws RepositoryException
	{
		return repository.get( id );
	}
	
	/**
	 * Método que retorna todos os membros cuja data de nascimento
	 * está contida entre o período passado como parâmetro.
	 * @param startDate é a data inicial
	 * @param endDate é a data final
	 */
	public Iterator< Member > getIterator( Date startDate, Date endDate ) throws RepositoryException
	{
		Iterator< Member > ret;

		Vector< Member > vector = new Vector< Member >();
		
		if( startDate.afterMonthDay( endDate ) )
		{
			Date temp = startDate;
			startDate = endDate;
			endDate = temp;
		}
		
		Iterator< Member > members = getIterator();
		while( members.hasNext() )
		{
			Member member = members.next();
			Date memberBirth = new Date( member.getBirth().getTime() );
			
			if( memberBirth.betweenMonthDay( startDate, endDate ) )
			{
				vector.add( member );
			}
		}
		
		ret = new Iterator< Member >( vector );
		
		return ret;
	}
	
	public Iterator< Member > getIterator() throws RepositoryException
	{
		return repository.getIterator();
	}
	
	public void remove( int id ) throws RepositoryException
	{
		repository.remove( id );
	}
	
	public int size() throws RepositoryException
	{
		return repository.size();
	}
	
	public static void main( String[] args ) throws RepositoryException
	{
		MemberBusiness business = new MemberBusiness();
		//business.add( new Member( "Rebeca de Barros Albuquerque Ferreira", Gender.female, new Date(utils.Date.getTime( 21, 9, 1984 ) ), 1, "32510986", "emanuel.b.a.ferreira@gmail.com",true, 0 ) );
		Iterator< Member > it = business.getIterator( new Date( 24, 7, 0 ), new Date( 25, 12, 0 ) );
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}
